<template>
  <div class="track-list-container">
    <div class="track-list-main">
      <div class="track-list-top"
           v-if="urlParamObj.name">
        <!-- <span>{{ urlParamObj.name }}</span> -->
        <span>{{ urlParamObj.name }}</span>
        <span>({{ pagination.total }})</span>
      </div>
      <div :id="searchConditionContainerId"></div>
      <div class="track-list-header">
        <CommonCounter v-if="selectedRowKeys.length"
                       :total="pagination.total"
                       :currentSelected="selectedRowKeys.length"
                       @cancelSelected="cancelSelected" />
        <div class="toolbar-container">
          <CommonToolbar :allToolBtns="allToolBtns"
                         @buttonClick="buttonClick"> </CommonToolbar>
        </div>
        <div class="search-part">
          <a-input-search :placeholder="$i18n('collaboration.new.template.search.keyWords')"
                          style="width: 272px"
                          :allowClear="true"
                          @search="onSearch" />
          <div class="condition-container">
            <SearchCondition :containerParentId="searchConditionContainerId"
                             :conditions="searchConditions"
                             @valueChange="conditionFilter"
                             @expandChange="expandChange"></SearchCondition>
          </div>
        </div>
      </div>
      <div class="track-list-content">
        <AVirtuallyTable :row-selection="{
            columnWidth: 60,
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange
          }"
                         ref="avirtuallyTable"
                         rowKey="id"
                         :pagination="true"
                         :paginationOption="pagination"
                         :columns="columns"
                         size="small"
                         :loading="loading"
                         :localstorageKey="getLocalStorageKey"
                         :bordered="false"
                         :openVirtuallyModel="true"
                         :dataSource="dataSource"
                         :rightClickMenus="rightClickMenus"
                         :titleRightMenus="titleRightMenus"
                         @paginationChange="handleTableChange"
                         @paginationShowSizeChange="paginationShowSizeChange"
                         @rowClick="rowClick">
          <!-- 分类插槽 -->
          <span slot="categoryLabel"
                slot-scope="{ text, record }">
            <CategoryLabel :text="text"
                           :urlParams="urlParamObj"
                           :slotData="record">
            </CategoryLabel>
          </span>
          <!-- 当前待办人插槽 -->
          <span slot="currentNodesInfo"
                slot-scope="{ record, text }"
                class="current-nodes-column"
                :title="text"
                @click.stop="showFlowChart1(record)">
            {{ text }}
          </span>
          <!-- 标题插槽 -->
          <span slot="subject"
                slot-scope="{ record }">
            <subjectTitle :slotData="record"
                          :urlParams="urlParamObj"
                          :isWaitList="false">
            </subjectTitle>
          </span>
        </AVirtuallyTable>
      </div>
    </div>
  </div>
</template>

<script>
  import CommonToolbar from '../../components/common-toolbar/index';
  import CommonCounter from '../../components/common-counter/index';
  import SearchCondition from '@/components/search-condition/index.vue';
  import AVirtuallyTable from '@/ant-virtually-table/table.vue';
  import subjectTitle from './components/subject-title.vue';
  import CategoryLabel from './components/category-label.vue';
  import collaboration from '../../utils/collaboration.js';
  import smartCodeMixin from '../../mixins/smart-code-mixin';
  import { getParams, loadComponentsThemeDefaultCSS } from '../../utils';
  import { formatRequestDataToJSON } from '@/utils/api';
  import * as Fiber from 'fiber';
  export default {
    name: 'TrackList',
    components: {
      CommonToolbar,
      CommonCounter,
      SearchCondition,
      AVirtuallyTable,
      subjectTitle,
      CategoryLabel
    },
    mixins: [smartCodeMixin],
    data() {
      return {
        fromType: 0, //0是菜单和磁贴， 1是栏目更多
        allToolBtns: [
          {
            id: 'cancelTrack',
            name: this.$i18n('track.button.cancel.label') //取消跟踪
          }
        ],
        showCounter: false,
        loading: false,
        searchConditionContainerId: 'search-condition-container-parent',
        searchConditions: [],
        dataSource: [],
        condition: null,
        columns: [],
        selectedRowKeys: [],
        selectedRows: [],
        urlParamObj: {},
        titleRightMenus: {
          asc: true,
          desc: true,
          freeze: true,
          fieldset: true
        },
        pagination: {
          page: 1,
          // pageSize: 20,
          total: 0
          // pageSizeOptions: ['10', '20', '30', '40', '50'],
          // showTotal: (total) => `${this.$i18n('orgrole.total_items', total)}`,
          // showSizeChanger: true
        },
        searchValue: ''
      };
    },
    created() {
      this.urlParamObj = getParams(window.location.search);
      this.urlParamObj.name
        ? (this.urlParamObj.name = window.decodeURIComponent(this.urlParamObj.name))
        : '';
      this.fromType = this.urlParamObj.fragmentId ? 1 : 0;
      window._wfctxPath = window._ctxPath;
      this.getTableHeader();
      this.getTableData();
      loadComponentsThemeDefaultCSS(window._ctxPath + window._ctpSkinUrl);
    },
    mounted() {},
    computed: {
      getLocalStorageKey() {
        return window._currentUser.id + this.urlParamObj.pageKey;
      }
    },
    methods: {
      getTableHeader() {
        const headerParams = {
          key: 'TRACK_SECTION',
          // 终端 0 pc 1 mobile （取值参照PlatformType）
          platform: 0
        };
        //来自栏目
        if (this.fromType == 1) {
          headerParams.arguments = {
            fragmentId: this.urlParamObj.fragmentId,
            ordinal: this.urlParamObj.ordinal,
            bigTitleIndex: this.urlParamObj.bigTitleIndex,
            userId: window._currentUser.id
          };
        }
        const url = `${window._ctxPath}/rest/global/metadata/list`;
        window.axios.post(url, headerParams).then((res) => {
          if (res.data.code === 0) {
            const resData = res.data.data;
            const colunmsArr = [];
            resData?.tableColumns.forEach((item) => {
              if (item.type != 'CHECKBOX') {
                let column = {
                  title: item.title,
                  width: item.width,
                  dataIndex: item.key,
                  ellipsis: true,
                  key: item.key,
                  fixed: false,
                  dropdownMenus: {
                    asc: true,
                    desc: true,
                    freeze: true,
                    fieldset: true
                  }
                };
                if (item.key == 'categoryLabel') {
                  column.scopedSlots = { customRender: 'categoryLabel' };
                } else if (item.key == 'currentNodesInfo') {
                  column.scopedSlots = { customRender: 'currentNodesInfo' };
                } else if (item.key == 'subject') {
                  column.scopedSlots = { customRender: 'subject' };
                }
                column.customCell = () => {
                  return {
                    style: {
                      padding: '0px 8px',
                      cursor: 'pointer'
                    }
                  };
                };
                colunmsArr.push(column);
              }
            });
            this.searchConditions = resData.searchConditions.filter((item) => item.key !== 'subject');
            this.columns = colunmsArr;
            const globalParam = resData.globalParam;
            this.supportSmartCode = globalParam ? globalParam.supportSmartCode : undefined;
            if (this.isHaveSmartCodePermission()) {
              this.allToolBtns.push(this.smartCodeBtnInfo);
            }
          }
        });
      },
      getTableData() {
        this.$refs.avirtuallyTable && this.$refs.avirtuallyTable.cleanSelection();
        this.loading = true;
        const { fragmentId = '', ordinal = '', bigTitleIndex = '' } = this.urlParamObj;
        // this.selectedRowKeys = [];
        let getDataParam = {
          fragmentId,
          state: '',
          ordinal,
          // sectionName: this.urlParamObj.section,
          bigTitleIndex,
          isTrack: 'true',
          condition: 'subject',
          textfield: this.searchValue,
          subject: this.searchValue,
          ...this.condition
        };
        if (this.condition) {
          getDataParam.condition = 'comQuery';
          delete getDataParam.textfield;
        }
        const sendParams = [
          { page: this.pagination.page, size: this.pagination.pageSize },
          getDataParam
        ];
        const managerName = 'pendingManager';
        const managerMethod = 'getMoreList4SectionContion';
        this.ajaxDo(managerName, managerMethod, sendParams)
          .then((data, err) => {
            this.loading = false;
            console.log(err, 'err');
            console.log(data, 'resultresult');
            const result = data.data;
            if (result) {
              this.pagination.total = result.total;
              this.pagination.page = result.page;
              this.dataSource = result.data;
            }
            window.parent.refreshMenuList && window.parent.refreshMenuList();
          })
          .catch((err) => {
            this.loading = false;
            console.log(err);
          });
      },
      conditionFilter(condition) {
        this.pagination.page = 1;
        //重要程度，状态
        const enumKeys = [
          'importLevel',
          'importantLevel',
          'importantLevelList',
          'subState',
          'subStateList'
        ];
        Object.keys(condition).forEach((key) => {
          if (enumKeys.includes(key)) {
            condition[key] = condition[key].join(',');
          }
        });
        //创建时间
        if (condition.createDate) {
          condition.createDate = condition.createDate.startDate + '#' + condition.createDate.endDate;
        }
        this.condition = condition;
        this.getTableData();
      },
      expandChange(isExpanded) {
        this.$nextTick(() => {
          this.$refs.avirtuallyTable && this.$refs.avirtuallyTable.resizeTable();
        });
        console.log(this.$refs.avirtuallyTable.resize);
        console.log(isExpanded, 'isExpanded');
      },
      //点击穿透
      rowClick(row) {
        let url = '';
        const {
          id: affairId,
          state,
          applicationCategoryKey: app,
          applicationSubCategoryKey: subApp
        } = row;
        if (app == 4) {
          //表单公文
          let from = 'Done';
          let openFrom = 'listDone';
          if (state == 2) {
            from = 'sended';
            openFrom = 'listSent';
          } else if (state == 3) {
            from = 'Pending';
            openFrom = 'listPending';
          }
          if (subApp == 1 || subApp == 2 || subApp == 3 || subApp == 4) {
            //新公文
            url =
              window._ctxPath +
              '/govdoc/govdoc.do?method=summary&affairId=' +
              affairId +
              '&openFrom=' +
              openFrom;
          } else if (subApp == 19 || subApp == 20 || subApp == 21) {
            //老公文
            url =
              window._ctxPath +
              '/edocController.do?method=detailIFrame&affairId=' +
              affairId +
              '&from=' +
              from;
          }
        } else if (app == 32) {
          //信息报送
          if (state == 2) {
            url =
              window._ctxPath +
              '/info/infoDetail.do?method=summary&openFrom=Send&affairId=' +
              affairId;
          } else if (state == 3) {
            url =
              window._ctxPath +
              '/info/infoDetail.do?method=summary&openFrom=Pending&affairId=' +
              affairId;
          } else {
            url =
              window._ctxPath +
              '/info/infoDetail.do?method=summary&openFrom=Done&affairId=' +
              affairId;
          }
        } else {
          //协同
          //默认已发
          let from = 'listSent';
          if (state === 1) {
            from = 'listWaitSend';
          } else if (state === 2) {
            from = 'listSent';
          } else if (state === 3) {
            from = 'listPending';
          } else if (state === 4) {
            from = 'listDone';
          }
          url =
            window._ctxPath +
            '/collaboration/collaboration.do?method=summary&openFrom=' +
            from +
            '&affairId=' +
            affairId +
            '&showTab=true';
        }
        this.showSummayDialogByURL(url);
      },
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys;
        this.selectedRows = selectedRows;
      },
      onSearch(e) {
        this.searchValue = e;
        this.pagination.page = 1;
        this.getTableData();
      },
      cancelSelected() {
        this.showCounter = false;
        // this.selectedRows = [];
        // this.selectedRowKeys = [];
        this.$refs.avirtuallyTable && this.$refs.avirtuallyTable.cleanSelection();
      },
      //按钮点击事件
      buttonClick(buttonKey) {
        switch (buttonKey) {
          case 'cancelTrack':
            this.cancelTrack();
            break;
          case 'smartCodeScan': // 扫一扫
            this.showSmartCode && this.showSmartCode();
            break;
        }
      },
      //取消跟踪
      cancelTrack() {
        if (this.selectedRowKeys.length === 0) {
          Fiber.message.warning($.i18n('collaboration.track.choose'));
          return;
        }
        let affairIds = [];
        this.selectedRows.forEach((row) => {
          affairIds.push(row.id);
        });
        // $('#affairId').val(affairId);
        var confirm = $.confirm({
          msg: $.i18n('collaboration.moreTrack.sureCancelTrack'), //确定取消跟踪事项吗？
          ok_fn: () => {
            const args = `CSRFTOKEN&_json_params=${JSON.stringify({
              fragmentId: this.urlParamObj.fragmentId || '',
              ordinal: this.urlParamObj.ordinal || '2',
              state: '',
              isTrack: 'true',
              bigTitleIndex: this.urlParamObj.ordinal || '',
              affairId: affairIds.join(',')
            })}`;
            let rowStr = this.columns
              .map((item) => {
                return item.key;
              })
              .join(',');
            const url = `${
              window._ctxPath
            }/portalAffair/portalAffairController.do?method=cancelTrack&rowStr=${rowStr}&columnsName=${window.encodeURI(
              this.urlParamObj.name || ''
            )}`;
            window.axios
              .post(url, args, {
                headers: {
                  'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
                }
              })
              .then((result) => {
                console.log(result);
                this.selectedRowKeys = [];
                this.getTableData();
              })
              .catch((err) => {
                console.log(err);
              });
          },
          cancel_fn: () => {
            confirm.close();
          }
        });
      },
      //显示流程图
      showFlowChart1(record) {
        const { caseId, processId, activityId, applicationCategoryKey, bodyType } = record;
        let options = {
          targetWin: window.getCtpTop(),
          caseId: caseId,
          processId: processId,
          isTemplate: false,
          showHastenButton: false,
          appName: applicationCategoryKey,
          currentNodeId: activityId,
          scene: 3,
          canExePrediction: bodyType === '20' && window._hasPlugin('workflowAdvanced')
        };
        window.showDiagram(options);
      },
      handleTableChange(page, pageSize) {
        this.pagination.page = page;
        this.pagination.pageSize = pageSize;
        this.getTableData();
      },
      paginationShowSizeChange(current, size) {
        console.log(current, size);
        this.pagination.page = 1;
        this.pagination.pageSize = size;
        this.getTableData();
      },
      ajaxDo(method, managerMethod, sendData) {
        const args = `managerMethod=${managerMethod}&arguments=${formatRequestDataToJSON(sendData)}`;
        const url = `${window._ctxPath}/ajax.do?method=ajaxAction&managerName=${method}&rnd=97448`;
        return window.axios.post(url, args, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
          }
        });
      },
      getSmartCodeDecodeParam() {
        const { fragmentId, ordinal, bigTitleIndex } = this.urlParamObj;
        const obj = {
          fragmentId,
          ordinal,
          bigTitleIndex,
          state: '',
          isTrack: true,
          ...this.condition
        };
        obj.openFrom = 'moreTrack';
        return obj;
      },
      // 智码扫码成功后回调
      smartCodeCallBack(data) {
        collaboration.smartCodeCallBack(data);
      },
      showSummayDialogByURL(url) {
        //公文、协同都是affairId，会议是Id
        var affairIdIndex = url.indexOf('affairId');
        var idIndex = url.indexOf('id');
        var id = '';
        if (affairIdIndex != -1) {
          id = window.getMultyWindowId('affairId', url);
          this.openWindow({ url: url, id: id });
        } else if (idIndex != -1) {
          id = window.getMultyWindowId('id', url);
          this.openWindow({ url: url, id: id });
        } else {
          this.openWindow({ url: url });
        }
      },
      openWindow(obj) {
        const url = obj.url;
        const a8Top = window.getA8Top();
        if (a8Top.isMultipleTabs && url.indexOf('showTab=true') != -1 && !this.isOcipSummary(obj)) {
          a8Top.openCtpWindow(obj);
        } else {
          window.openCtpWindow(obj);
        }
      },
      //ocip推送过来的数据，不走多页签
      isOcipSummary(obj) {
        if (window._hasPlugin('ocip')) {
          let url = obj.url;
          if (url.indexOf('method=summary&') != -1 && url.indexOf('showTab=true') != -1) {
            let params = url.split('&');

            for (let i = 0; i < params.length; i++) {
              if (params[i].indexOf('affairId=') == -1) {
                continue;
              }
              let affairIds = params[i].split('=');
              if (affairIds[0] == 'affairId' && affairIds[1]) {
                return window.callBackendMethod(
                  'ocipColManager',
                  'checkIsExchangeAffair',
                  affairIds[1]
                );
              }
            }
          }
        }
        return false;
      }
    }
  };
</script>

<style>
  @import url('../../assets/css/common.css');
</style>
<style lang="scss">
  .track-list-container {
    position: relative;
    height: 100%;
    .track-list-main {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      top: 0;
      display: flex;
      padding-left: 16px;
      flex-direction: column;
      background-color: #ffffff;

      .track-list-top {
        padding: 12px 16px 0 0;
        font-size: 16px;
        font-weight: 600;
        color: #333333;
      }

      .track-list-header {
        display: flex;
        padding: 12px 16px 12px 0;
        height: 54px;
        box-sizing: border-box;

        .toolbar-container {
          flex: 1;
          overflow: hidden;
        }
      }

      .search-part {
        // flex: 1;
        display: flex;
        justify-content: flex-end;
        overflow: hidden;
        margin-left: 100px;

        .condition-container {
          margin-left: 12px;
          display: flex;
        }
      }

      .track-list-content {
        flex: 1;
        padding: 0;

        .current-nodes-column {
          cursor: pointer;
          &:hover {
            color: #2490f8;
            color: var(--theme-brand5, #2490f8);
          }
        }
      }
    }
  }
</style>
